﻿<!DOCTYPE html>
<html>
<head>
    <title>天气查询</title>
    <meta charset="utf-8" />
    <script src="~/lib/jquery/dist/jquery.js"></script>
</head>
<body>
   
    <style>
        #pic {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin: 20px auto;
            cursor: pointer;
        }
    </style>
    <div class="text-center">
        <div>
            <img id="pic" src="../Photos/20220612110701.jpg">
            <input id="upload" name="file" type="file" style="display: none" />
            <input id="doUpload" type="button" value="确认上传" />
        </div>
        <script>
            //技术交流qq群：1158377441
            $(function () {
                var file;
                //选图片，预览
                $("#pic").click(function () {

                    $("#upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
                    $("#upload").on("change", function () {
                        var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
                        if (objUrl) {
                            $("#pic").attr("src", objUrl); //将图片路径存入src中，显示出图片
                        }
                        file = this.files[0];
                    });
                });

                //确认上传
                $("#doUpload").click(function () {
                    if (file) {
                        var data = new FormData();
                        data.append("file", file);
                        $.ajax({
                            type: "post",
                            url: "/api/test/UploadPhotosAsyncWithJq",
                            data: data,
                            contentType: false,
                            //默认文件类型application/x-www-form-urlencoded  设置之后multipart/form-data
                            processData: false,
                            // 默认情况下会对发送的数据转化为对象 不需要转化的信息
                            success: function (res) {
                                alert("上传成功");
                            },
                        });
                    }
                })
            });

            //建立一個可存取到該file的url
            function getObjectURL(file) {
                var url = null;
                if (window.createObjectURL != undefined) { // basic
                    url = window.createObjectURL(file);
                } else if (window.URL != undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file);
                } else if (window.webkitURL != undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file);
                }
                return url;
            }
        </script>
    </div>

</body>
</html>